package com.brooks.demo.program.p3;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 要求用两个线程，顺序打印1A2B,一个打印数字，一个打印字母
 *
 * @Author mihutu
 * @Date 2020/10/21 17:13
 * @Version 1.0
 */
public class Demo1 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        CountDownLatch latch = new CountDownLatch(2);
         Lock lock = new ReentrantLock();
         Condition t1 = lock.newCondition();
         Condition t2 = lock.newCondition();

        new Thread(()->{
            lock.lock();
            try {
                for (int i=1;i<27;i++){
                    System.out.println(i);
                    sb.append(i);
                    t2.signal();
                    t1.await();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
            latch.countDown();
        }).start();
        new Thread(()->{
            lock.lock();
            try {
                String name;
                for (int i=0;i<26;i++){
                    name = String.valueOf((char)(97+i)).toUpperCase();
                    System.out.println(name);
                    sb.append(name);
                    t1.signal();
                    t2.await();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
            latch.countDown();
        }).start();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(sb.toString());
    }
}
